<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.4.0/sockjs.min.js"></script>
    <script src="./lib/stomp.js"></script>
    <script>
        var stompClient = null;

        function connection(userId) {
            // 建立连接对象
            var url = "http://127.0.0.1:8000/ws-homehub/ws?userId=" + userId;
            var socket = new SockJS(url);
            // 获取STOMP子协议的客户端对象
            stompClient = Stomp.over(socket);
            // 定义客户端的认证信息,按需求配置
            var headers = {
                token: "test-token"
            };
            // 向服务器发起websocket连接
            stompClient.connect(headers, function connectCallback(frame) {
                    // 订阅广播级别的消息
                    stompClient.subscribe("/topic/device.12312", function (msg) {
                        // 接收回调
                        console.log("接收广播消息成功")
                        //有多个subscribe时，接收到消息会走最后一个回调函数
                        // 订阅服务端提供的某个topic
                        let body = JSON.parse(msg.body);
                        var $p = document.createElement('p');
                        $p.innerText = body.content + '----' + dateFtt(new Date())
                        document.getElementById('content').appendChild($p);
                    });
                    // 订阅用户级别的消息
                    stompClient.subscribe("/user/queue/point", function (msg) {
                        // 接收回调
                        console.log("接收用户消息成功")
                        //有多个subscribe时，接收到消息会走最后一个回调函数
                        // 订阅服务端提供的某个topic
                        let body = JSON.parse(msg.body);
                        var $p = document.createElement('p');
                        $p.innerText = body.content + '----' + dateFtt(new Date())
                        document.getElementById('content').appendChild($p);
                    });
                },
                function errorCallBack(error) {
                    // 连接失败时（服务器响应 ERROR 帧）的回调方法
                    console.log("连接失败");
                });
        }

        function dateFtt(date, fmt) {
            if (!fmt) {
                fmt = 'yyyy-MM-dd hh:mm:ss'
            }
            var o = {
                "M+": date.getMonth() + 1,                 //月份
                "d+": date.getDate(),                    //日
                "h+": date.getHours(),                   //小时
                "m+": date.getMinutes(),                 //分
                "s+": date.getSeconds(),                 //秒
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds()             //毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }

        window.onload = function () {
            connection(10000);
        }

        function handleSend() {
            var msg = document.getElementById('sendMsg').value;
            // 发送到topic接口
            stompClient.send('/topic/device.12312', {}, JSON.stringify({content: msg}));
        }

    </script>
</head>
<body>
<div><input type="text" id="sendMsg">
    <button onclick="handleSend()">发送</button>
</div>
<div id="content"></div>
</body>
</html>
